package cn.school.demo.ui.history

import android.annotation.SuppressLint
import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.R
import cn.school.demo.databinding.FragmentHistoryViewPageSubjectBinding
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.reflect.TypeToken
import com.mylhyl.circledialog.CircleDialog

class HistoryViewPageSubjectFragment : Fragment() {

    companion object {
        fun newInstance() = HistoryViewPageSubjectFragment()
    }

    private lateinit var binding: FragmentHistoryViewPageSubjectBinding
    private lateinit var viewModel: HistoryViewPageSubjectViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(HistoryViewPageSubjectViewModel::class.java)
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_history_view_page_subject,
            container,
            false
        )
        init()
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun init() {
        viewModel.getList().observe(viewLifecycleOwner) {
            if (it != null) {
                if (it.success) {
                    it.data["answer"]?.let { jsonData ->
                        try {
                            val list = GsonUtils.fromJson<MutableList<String>>(
                                jsonData.toString(),
                                object : TypeToken<MutableList<String>>() {}.type
                            )
                            if (list.size == 0) {
                                binding.historyFragmentSubjectRecyclerviewNoData.visibility =
                                    View.VISIBLE
                                binding.historyAnswerProgressBar.visibility = View.GONE
                            } else {
                                binding.historyAnswerProgressBar.visibility = View.GONE
                                viewModel.updateSubjectList(list)
                                binding.historySubjectFragmentRecyclerview.apply {
                                    adapter?.notifyDataSetChanged() ?: let {
                                        layoutManager = LinearLayoutManager(requireContext())
                                        adapter = SubjectBrowseAdapter(viewModel.subjectList)
                                    }
                                }
                            }
                        } catch (e: Error) {
                            e.printStackTrace()
                        }
                    } ?: let {
                        LogUtils.e("获得答题记录http返回值的data[\"answer\"]为空！")
                        CircleDialog.Builder().setTextColor(Color.RED).setText("网络异常，请检查网络重试！")
                            .setNegative("确定", null)
                            .show(parentFragmentManager)
                    }
                } else {
                    if (it.message == "用户暂无作答记录！") {
                        binding.historyFragmentSubjectRecyclerviewNoData.visibility =
                            View.VISIBLE
                        binding.historyAnswerProgressBar.visibility = View.GONE
                    } else {
                        CircleDialog.Builder().setTextColor(Color.RED).setText(it.message)
                            .setNegative("确定", null)
                            .show(parentFragmentManager)
                        LogUtils.e(it.message)
                    }
                }
            } else {
                CircleDialog.Builder().setTextColor(Color.RED).setText("网络异常，请检查网络重试！")
                    .setNegative("确定", null)
                    .show(parentFragmentManager)
            }
        }
    }

    private inner class SubjectBrowseHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val titleTextView =
            itemView.findViewById<TextView>(R.id.history_recycler_view_text)

        @SuppressLint("NewApi")
        fun bind(s: String) {
            titleTextView.text = s
        }
    }

    private inner class SubjectBrowseAdapter(var subjectBrowseList: MutableList<String>) :
        RecyclerView.Adapter<SubjectBrowseHolder>() {

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): SubjectBrowseHolder {
            return SubjectBrowseHolder(
                layoutInflater.inflate(
                    R.layout.list_item_history,
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: SubjectBrowseHolder, position: Int) {
            val subjectBrowse = subjectBrowseList[position]
            holder.bind(subjectBrowse)
        }

        override fun getItemCount() = subjectBrowseList.size

    }
}